package com.cb.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cb.dto.AssignRoleDto;
import com.cb.dto.CurrentUser;
import com.cb.dto.UserDto;
import com.cb.entity.Role;
import com.cb.entity.User;
import com.cb.service.RoleService;
import com.cb.service.UserRoleService;
import com.cb.service.UserService;
import com.cb.utils.Result;
import com.cb.utils.TokenUtils;
import com.cb.utils.WarehouseConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询用户的url接口/user/user-list
     */
    @GetMapping("/user-list")
    public Result userListPage(User user,int pageNum,int pageSize){
        Page<UserDto> userDtoPage = userList(user, pageNum, pageSize);
        return Result.ok(userDtoPage);
    }

    public Page<UserDto> userList(User user,int pageNum,int pageSize){
            Page<User> pageInfo = new Page<>(pageNum, pageSize);
            Page<UserDto> userDtoPage = new Page<>();
            userService.getUser(pageInfo,user);

        BeanUtils.copyProperties(pageInfo,userDtoPage,"records");
        List<User> records = pageInfo.getRecords();
        List<UserDto> list=records.stream().map((item)->{
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item,userDto);
            //根据create_by查询名字
            int createBy = item.getCreateBy();
            User user1 = userService.getNameByCreateId(createBy);
            if (user1!=null) {
                String userCode = user1.getUserCode();
                userDto.setCreateByName(userCode);
            }
            return userDto;
        }).collect(Collectors.toList());
        userDtoPage.setRecords(list);
        return userDtoPage;
    }

    /**
     * 添加用户的url接口/user/addUser
     */
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user,
                          @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)String token){
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id,即创建新用户的用户id
        int userId = currentUser.getUserId();
        user.setCreateBy(userId);
        return userService.addUser(user);
    }

    /**
     * 修改用户状态的url接口/user/updateState
     */
    @PutMapping("/updateState")
    public Result updateUserState(@RequestBody User user,
                                  @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //需要user中的userId和userState
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id,即创建新用户的用户id
        int userId = currentUser.getUserId();
        //设置修改用户的用户id和修改时间
        user.setUpdateBy(userId);
        user.setUpdateTime(new Date());
        user.setUserState(user.getUserState());
        boolean b = userService.updateById(user);
        if(b){
            return Result.ok("修改成功！");
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS, "修改失败！");
        }
    }

    /**
     * 查询用户已分配的角色的url接口/user/user-role-list/{userId}
     */
    @GetMapping("/user-role-list/{userId}")
    public Result userRoleList(@PathVariable Integer userId){
        List<Role> roleList= roleService.queryRolesByUserId(userId);
        return Result.ok(roleList);
    }

    /**
     * 给用户分配角色的url接口/user/assignRole
     */
    @PutMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleDto assignRoleDto){
        roleService.assign(assignRoleDto);
        return Result.ok("分配角色成功！");
    }

    /**
     * 删除用户的url接口/user/deleteUser/{userId}
     */
    @DeleteMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable Integer userId){
        userService.deleteUser(userId);
        return Result.ok("用户删除成功！");
    }

    /**
     * 批量删除的url接口/user/deleteUserList
     */
    @DeleteMapping("/deleteUserList")
    public Result deleteUserList(@RequestBody List<Integer> userIds){
        int result = userService.deleteUserList(userIds);
        if(result>0){
            return Result.ok("用户删除成功！");
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS,"用户删除失败！");
        }
    }

    /**
     * 修改用户的url接口/user/updateUser
     */
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user,
                             @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //获取当前登录的用户
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //获取当前登录的用户id -- 修改用户的用户id
        int updateBy = currentUser.getUserId();
        System.out.println("-----------------"+updateBy);
        user.setUpdateBy(updateBy);
        return userService.updateUserName(user);
    }

    /**
     * 重置密码的url接口/user/updatePwd/{userId}
     */
    @PutMapping("/updatePwd/{userId}")
    public Result resetPassWord(@PathVariable Integer userId){
        return userService.resetPassWord(userId);
    }

    /**
     * 导出数据的url接口/user/exportTable
     */
    @GetMapping("/exportTable")
    public Result exportTable(User user,int pageNum,int pageSize){
        Page<UserDto> userDtoPage = userList(user, pageNum, pageSize);
        return Result.ok(userDtoPage.getRecords());
    }

}
